package com.milk.utils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.milk.web.config.SystemConfig;
import com.xiaoleilu.hutool.crypto.symmetric.SymmetricAlgorithm;
import com.xiaoleilu.hutool.crypto.symmetric.SymmetricCrypto;
import com.xiaoleilu.hutool.util.StrUtil;

public class CookieUtils {
	
	private static byte[] encode_key = {9,0,1,7,0,6,1,2,3,4,5,6,7,8,9,-1};
	
	private static SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, encode_key);

	
	public static String getCookieValue(HttpServletRequest request,String key){
		Cookie[] cookies = request.getCookies();
		
		for(Cookie cookie : cookies){
			if(cookie.getName().equals(key)){
				return cookie.getValue();
			}
		}
		return "";
		
	}
	
	public static String getDecodeCookieValue(HttpServletRequest request,String key){
		
		String value = getCookieValue(request,key);
		
		if(StrUtil.isNotEmpty(value)){
			return aes.decryptStr(value);
		}
		return value;
	}
	
	
	public static void setEncodeCookieValue(HttpServletResponse response,String key,String value,String domain,int secondAge){
		
		value = aes.encryptHex(value);
		
		setCookieValue(response,key,value,domain,secondAge);
		
	}
	
	public static void setCookieValue(HttpServletResponse response,String key,String value,String domain,int secondAge){
		Cookie cookie = new Cookie(key,value);
		cookie.setDomain(domain);
		cookie.setMaxAge(secondAge);
		response.addCookie(cookie);
	}
	
	public static void main(String[] args) {
		System.out.println(aes.encryptHex("901706"));
		System.out.println(aes.decryptStr("45be4e49e1fc6e29ecf3545fa17cc03b"));
	}

	public static void delCookie(HttpServletResponse response, String key, String host) {
		setCookieValue(response, key, "", host, 0);
	}
	
}
